/**
 * 设备状态变更反馈流程 demo
 * @author 陈浩杰
 */
const {randomNum} = require('../../../../util/number');
const {client, deviceCode} = require('../../mqtt');
const {productCode, sn} = require('../mqtt_report_event');
const moment = require('moment');

client.on('connect', () => {
    client.subscribe([`thing/down/action/${productCode}/${deviceCode}`], {qos: 2}, err => {
        if (!err) {
            console.log(`thing/down/action/${productCode}/${deviceCode}`, '订阅成功')
        }
    })

    // 向主题 subscribe/report/${仪表apk定制开发商标识}/${deviceCode} 主题发布 订阅成功消息
    const req = {}
    req.ts = moment().format('YYYYMMDDHHmmssSSS')
    req.traceId = deviceCode + '.' + moment().format('YYYYMMDDHHmmssSSS') + '.' + randomNum(6)
    req.productCode = productCode
    req.sn = sn
    req.deviceCode = deviceCode
    req.user = {userKey: '', sessionId: ''}
    req.success = true
    req.errorMsg = ''
    // 01：锁定界面中；02运动中；03：暂停中；04：解锁但未开始运动中；05：气阻产品测试状态
    req.data = {
        eventType: 'info',
        eventCode: 'info_01',
        eventValue: {preStatus: '', currentStatus: '01', sportModeName: '01'}
    }
    const reqJsonStr = JSON.stringify(req)
    console.log(req.traceId, '设备事件变更上报消息体\n', reqJsonStr)
    client.publish(`thing/up/event/${productCode}/${deviceCode}`, reqJsonStr, {qos: 2});

})

client.on('message', (topic, message) => {
    const messageJson = JSON.parse(message.toString());
    console.log(messageJson)
})
